package com.xuecheng.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.auth.dto.AuthParamsDto;
import com.xuecheng.auth.dto.XcUserExt;
import com.xuecheng.auth.entity.UserMember;
import com.xuecheng.auth.mapper.UserMemberMapper;
import com.xuecheng.auth.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * ClassName: PasswordAuthServiceImpl
 * Package: com.xuecheng.auth.service.impl
 * Description:  账号密码认证
 *
 * @Author 看到风
 * @Create 2024/10/22 15:57
 * @Version 1.0
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
    @Autowired
    UserMemberMapper userMemberMapper;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //账号
        String username = authParamsDto.getUsername();
        UserMember user = userMemberMapper.selectOne(new LambdaQueryWrapper<UserMember>().eq(UserMember::getUserId, username));
        if(user==null){
        //返回空表示用户不存在
            throw new RuntimeException("账号不存在");
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(user,xcUserExt);
        //校对身份
        if(!authParamsDto.getIdentity().equals(user.getIdentity().toString())){
            throw new RuntimeException("账号不合法");
        }
        //校验密码
        //取出数据库存储的正确密码
        String passwordDb =user.getPassword();
        String passwordForm = authParamsDto.getPassword();
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if(!matches){
            throw new RuntimeException("账号或密码错误");
        }
        return xcUserExt;
    }
}
